package web.file;

import util.FANREN;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@WebServlet(name = "DownloadServlet",urlPatterns = {"/download"})
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //String fileName = FANREN.getJson(request);
        String fileName = request.getParameter("fileName");
        System.out.println(fileName);
        FileInputStream fis = new FileInputStream(request.getServletContext().getRealPath("")+"files"+File.separator+fileName);
        System.out.println(request.getServletContext().getRealPath("")+"files"+File.separator+fileName);
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);
        OutputStream os = response.getOutputStream();
        byte[] buf = new byte[1024];
        int l = -1;
        while((l = fis.read(buf))!=-1){
            os.write(buf,0,l);
            os.flush();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
